package main

import (
	"database/sql"
	"fmt"
	"io/ioutil"
	"log"
	"os"

	_ "modernc.org/sqlite"
)

func main() {
	dbFile := "db.sqlite3"
	schemaFile := "schema.sql"

	if _, err := os.Stat(dbFile); err == nil {
		fmt.Printf("%s already exists, removing...\n", dbFile)
		if err := os.Remove(dbFile); err != nil {
			log.Fatalf("remove existing db failed: %v", err)
		}
	}

	schemaBytes, err := ioutil.ReadFile(schemaFile)
	if err != nil {
		log.Fatalf("read schema file failed: %v", err)
	}

	db, err := sql.Open("sqlite", dbFile)
	if err != nil {
		log.Fatalf("open sqlite db failed: %v", err)
	}
	defer db.Close()

	if _, err := db.Exec(string(schemaBytes)); err != nil {
		log.Fatalf("exec schema failed: %v", err)
	}

	fmt.Printf("created %s successfully\n", dbFile)
}
